import java.util.Arrays;
import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Gao zhao xu
 * Date: 2023-12-04
 * Time: 上午 09:52
 */
public class Test4 {
    /**
     * 插入排序
     */
    public static void insertSort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            int tmp = arr[i];
            int j = i - 1;
            for (; j >= 0; j--) {
                if (arr[j] > tmp)  arr[j + 1] = arr[j];
                else break;
            }
            arr[j + 1] = tmp;
        }
    }

    /**
     * 希尔排序
     */
    public static void shellSort(int[] arr) {
        int gap =arr.length;
        while (gap > 1) {
            gap /= 2;
            shell(arr, gap);
        }
    }
    public static void shell(int[] arr, int gap) {
        for (int i = gap; i < arr.length; i++){
            int tmp = arr[i];
            int j = i - gap;
            for (;j >= 0; j -= gap) {
                if (arr[j] > tmp) {
                    arr[j + gap] = arr[j];
                }else break;
            }
            arr[j + gap] = tmp;
        }
    }

    /**
     * 选择排序
     */
    public static void selectSort(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            int min = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[min]) {
                    min = j;
                }
            }
            int tmp = arr[min];
            arr[min] = arr[i];
            arr[i] = tmp;
        }
    }

    /**
     * 堆排序
     */
    public static void heapSort(int arr[]) {
        makeBigHeap(arr);
        int end = arr.length - 1;
        while (end > 0) {
            int tmp = arr[0];
            arr[0] = arr[end];
            arr[end] = tmp;
            shiftDown(arr, 0, end);
            end--;
        }
    }
    public static void makeBigHeap(int[] arr) {
        for (int i = (arr.length - 1 - 1) / 2; i > 0; i--){
            shiftDown(arr,i,arr.length);
        }
    }
    public static void shiftDown(int[] arr, int parent, int end) {
        int child = parent *2 + 1;
        while (child < end) {
            if (child + 1 < end) {
                child = arr[child] > arr[child + 1] ? child : child + 1;
            }
            if (arr[child] > arr[parent]) {
                int tmp = arr[child];
                arr[child] = arr[parent];
                arr[parent] = tmp;
                parent = child;
                child = parent *2 + 1;
            } else break;
        }
    }
    public static void main(String[] args) {
        int[] arr = {5,1,9,4,2};
        heapSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
